<template>
  <el-dialog v-model="ifShow" title="新增订单" width="70vw" :before-close="handleCancel">
    <div id="map" style="height: 200px; width: 100%; margin: 40px 0"></div>
    <el-form ref="ruleForm" :model="formData" :rules="rules" label-width="auto" status-icon>
      <el-row>
        <el-col :span="8">
          <el-form-item label="订单类型" prop="orderType">
            <el-select @change="handleOrderTypeChange" clearable v-model="formData.orderType" placeholder="请选择">
              <el-option v-for="item in orderTypeArr" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <!--105接机  -->
        <el-col :span="8" v-if="formData.orderType == 106">
          <el-form-item label="上车地址">
            <el-input placeholder="搜索地点" v-model="searchQuery1" />
            <div :class="['ul_box', searchResults1.length ? 'ul_h' : '']">
              <template v-for="(item, index) in searchResults1" :key="index">
                <div v-if="isFromAddress" class="item" @click="onLocationSelect(index, 1)">
                  {{ item.name }}
                </div>
              </template>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="formData.orderType == 105">
          <el-form-item label="上车地址" prop="fromName">
            <el-select @change="handlerFromChange" filterable clearable v-model="formData.fromName" placeholder="请选择">
              <el-option v-for="item in stationList" :key="item.id" :label="item.stationName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="formData.orderType == 105">
          <el-form-item label="下车地址">
            <el-input placeholder="搜索地点" v-model="searchQuery2" />
            <div :class="['ul_box', searchResults2.length ? 'ul_h' : '']">
              <template v-for="(item, index) in searchResults2" :key="index">
                <div v-if="isToAddress" class="item" @click="onLocationSelect(index, 2)">
                  {{ item.name }}
                </div>
              </template>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="formData.orderType == 106">
          <el-form-item label="下车地址" prop="toName">
            <el-select @change="handlerToChange" filterable clearable v-model="formData.toName" placeholder="请选择">
              <el-option v-for="item in stationList" :key="item.id" :label="item.stationName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="平台" prop="platformId">
            <el-select clearable v-model="formData.platformId" placeholder="请选择">
              <el-option v-for="item in platFormArr" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="渠道" prop="channelId">
            <el-select clearable v-model="formData.channelId" placeholder="请选择">
              <el-option v-for="item in channelArr" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="车型" prop="vehicleTypeId">
            <el-select clearable v-model="formData.vehicleTypeId" placeholder="请选择">
              <el-option v-for="item in carTypeArr" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="用车时间" prop="useTime">
            <el-date-picker
              type="datetime"
              style="width: 100%"
              showTime
              format="YYYY-MM-DD HH:mm:00"
              valueFormat="YYYY-MM-DD HH:mm:00"
              placeholder="请选择创建时间"
              v-model="formData.useTime"
              :disabledDate="disabledDateFn"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="乘客姓名" prop="passengerName">
            <el-input v-model="formData.passengerName" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="乘客电话" prop="passengerPhone">
            <el-input v-model="formData.passengerPhone" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="渠道订单号" prop="channelOrderId">
            <el-input v-model="formData.channelOrderId" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="乘客价格" prop="orderPrice">
            <el-input v-model="formData.orderPrice" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="航班号" prop="flightNo">
            <el-input style="width: 100%" v-model="formData.flightNo" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="formData.orderType == 201">
          <el-form-item label="包车天数" prop="days">
            <el-input-number style="width: 100%" v-model="formData.days" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleOk">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import AMapLoader from "@amap/amap-jsapi-loader";
import CommonApi from "@/api/common";
import OrderApi from "@/api/order";
import JntApi from "@/api/jnt";
import { watch, ref } from "vue";
const emit = defineEmits(["success"]);
let map: any = null;
const props = defineProps<{}>();
const ifShow = ref(false);
const searchQuery1 = ref(); //上车地址查询
const searchQuery2 = ref(); //下车地址查询
const searchResults1 = ref([]); //上车查询条件
const searchResults2 = ref([]); //下车查询条件
const placeSearch = ref(null); //地图搜索插件
const isFromAddress = ref(false); //地图搜索插件
const isToAddress = ref(false); //地图搜索插件
const preventWatch = ref(false); //控制是否触发搜索
const ruleForm = ref(null);
const platFormArr: any = [{ label: "贵宾专车", value: 6 }];
const channelArr: any = [{ label: "吉航", value: 12 }];
const orderTypeArr: any = [
  { label: "接机-港澳", value: 105 },
  { label: "送机-港澳", value: 106 },
];
const carTypeArr: any = [
  {
    label: "经济5座",
    value: 101,
  },
  {
    label: "舒适5座",
    value: 201,
  },
  {
    label: "豪华5座",
    value: 401,
  },
  {
    label: "商务7座",
    value: 301,
  },
];
let formData = ref({
  platformId: 6,
  channelId: 12,
  channelOrderId: "",
  id: "",
  orderType: "",
  vehicleTypeId: "",
  vehicleTypeName: "",
  orderPrice: "",
  useTime: "",
  passengerName: "",
  passengerPhone: "",
  fromLat: "",
  fromLng: "",
  fromName: "",
  toLat: "",
  toLng: "",
  toName: "",
  remark: "",
  flightNo: "",
});
const stationList = ref([]);
const rules = reactive({
  platformId: [{ required: true, message: "请选择" }],
  channelId: [{ required: true, message: "请选择" }],
  orderType: [{ required: true, message: "请选择" }],
  vehicleTypeId: [{ required: true, message: "请选择" }],
  channelOrderId: [{ required: true, message: "请输入" }],
  useTime: [{ required: true, message: "请选择" }],
  passengerName: [{ required: true, message: "请输入" }],
  passengerPhone: [{ required: true, message: "请输入" }],
  orderPrice: [{ required: true, message: "请输入" }],
});
watch(searchQuery1, (newVal) => {
  if (!preventWatch.value) {
    if (newVal) {
      onSearch(searchQuery1.value, 1);
    } else {
      searchResults1.value = [];
    }
  }
});
watch(searchQuery2, (newVal) => {
  if (!preventWatch.value) {
    if (newVal) {
      onSearch(searchQuery2.value, 2);
    } else {
      searchResults2.value = [];
    }
  }
});

const disabledDateFn = (time: any) => {
  return time.getTime() < Date.now() - 8.64e7;
};
const onSearch = (keyword, type) => {
  if (!placeSearch.value) {
    return;
  }
  placeSearch.value.search(keyword, (status, result) => {
    if (status === "complete" && result.info === "OK") {
      if (type == 1) {
        searchResults1.value = result.poiList.pois;
        isFromAddress.value = true;
      } else {
        searchResults2.value = result.poiList.pois;
        isToAddress.value = true;
      }
      // 假设this.map是你的AMap地图实例
      if (result.poiList.pois.length > 0) {
        const firstPoi = result.poiList.pois[0];
        map.setZoomAndCenter(17, [firstPoi.location.lng, firstPoi.location.lat]); // 街道级别的缩放是17
      }
    }
  });
};

const handlerFromChange = (id) => {
  let findObj = stationList.value.find((item) => item.id == id);

  formData.value.fromName = findObj.stationName; //出发地址
  formData.value.fromLng = findObj.point.split(",")[0]; //起点经度
  formData.value.fromLat = findObj.point.split(",")[1]; //起点维度
};
const handlerToChange = (id) => {
  let findObj = stationList.value.find((item) => item.id == id);
  formData.value.toName = findObj.stationName; //出发地址
  formData.value.toLng = findObj.point.split(",")[0]; //起点经度
  formData.value.toLat = findObj.point.split(",")[1]; //起点维度
};
const handleOrderTypeChange = () => {
  formData.value.fromName = "";
  formData.value.fromLng = "";
  formData.value.fromLat = "";
  formData.value.toName = "";
  formData.value.toLng = "";
  formData.value.toLat = "";
  searchQuery1.value = "";
  searchQuery2.value = "";
};
//点击搜索到每一项触发
const onLocationSelect = (index, type) => {
  let selectedPoi;
  if (type == 1) {
    selectedPoi = searchResults1.value[index];
  } else {
    selectedPoi = searchResults2.value[index];
  }
  if (!selectedPoi) return;
  preventWatch.value = true; // 不触发watch
  if (type == 1) {
    console.log("selectedPoi", selectedPoi);

    //上车
    // console.log('selectedPoi', selectedPoi);
    searchQuery1.value = selectedPoi.name;
    formData.value.fromName = selectedPoi.name; //出发地址
    // formData.departDetailAddress = selectedPoi.address;
    formData.value.fromLat = selectedPoi.location.lat; //起点维度
    formData.value.fromLng = selectedPoi.location.lng; //起点经度
    searchResults1.value = [];
    isFromAddress.value = false;
  } else {
    // 下车
    searchQuery2.value = selectedPoi.name;
    formData.value.toName = selectedPoi.name; //下车地址
    // formData.arriveDetailAddress = selectedPoi.address; //下车详细地址
    formData.value.toLat = selectedPoi.location.lat; //下车维度
    formData.value.toLng = selectedPoi.location.lng; //下车精度
    searchResults2.value = [];
    isToAddress.value = false;
  }
  const position = [selectedPoi.location.lng, selectedPoi.location.lat];
  placeMarker(position);
  setTimeout(() => {
    preventWatch.value = false;
  }, 0); // 控制可以搜索
};

const placeMarker = (position) => {
  new AMap.Marker({
    map: map,
    position: position,
  });
  map.setCenter(position);
};

function edit(row: any) {
  initMap();
  ifShow.value = true;
  JntApi.getStationList({ type: 1 }).then((res) => {
    if (res.code == 0) {
      stationList.value = res.result;
    }
  });
  formData.value = {
    platformId: 6,
    channelId: 12,
    channelOrderId: "",
    id: "",
    orderType: "",
    vehicleTypeId: "",
    vehicleTypeName: "",
    orderPrice: "",
    useTime: "",
    passengerName: "",
    passengerPhone: "",
    fromLat: "",
    fromLng: "",
    fromName: "",
    toLat: "",
    toLng: "",
    toName: "",
    remark: "",
    flightNo: "",
  };
}

/**
 * 确定按钮点击事件
 */
async function handleOk() {
  if (!formData.value.orderType) {
    ElMessage.error("请选择订单类型");
    return;
  }
  if (!formData.value.fromName) {
    ElMessage.error("请选择上车地址");
    return;
  }
  if (!formData.value.toName) {
    ElMessage.error("请选择下车地址");
    return;
  }
  if (formData.orderType == 201 && !formData.days) {
    alert("请输入包车天数");
    return;
  }

  await ruleForm.value.validate(async (valid, fields) => {
    if (valid) {
      OrderApi.orderAdd(formData.value).then((data) => {
        if (data.code == 0) {
          ElMessage.success(data.message);
          handleCancel();
          emit("success");
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
}

/**
 * 取消按钮回调事件
 */
function handleCancel() {
  searchQuery1.value = "";
  searchQuery2.value = "";
  searchResults1.value = [];
  searchResults2.value = [];
  ifShow.value = false;
}

//初始化查询地图
function initMap() {
  window._AMapSecurityConfig = {
    securityJsCode: "d9bb6af5397ae140433f57fc892608ad", // 申请key对应的秘钥 -> 注意了，如果不搭配密钥使用，搜索将没有结果
  };
  AMapLoader.load({
    key: "24e9f8aa4e598a8db6b458f78d29f93f", // 替换成你的高德地图key
    // key: '3e4c1f76807c5beae8aef6c4a6af69dd', // 替换成你的高德地图key
    version: "2.0",
    plugins: ["AMap.PlaceSearch", "AMap.Marker"], // 加载所需插件
  })
    .then((AMap) => {
      map = new AMap.Map("map", {
        zoom: 15,
        center: [116.397428, 39.90923],
      });
      placeSearch.value = new AMap.PlaceSearch({
        map: map,
      });
    })
    .catch((e) => {
      console.log(e);
    });
}

defineExpose({
  edit,
});
onMounted(() => {});
</script>
<style lang="scss" scoped>
.ul_h {
  height: 140px;
}
.ul_box {
  background: #fefefe;
  overflow: auto;
  .item {
    margin: 0 0 6px 10px;
  }
  .item:hover {
    background: #f5f5f5;
  }
}
.antd-modal-form {
  overflow-y: auto;
  padding: 24px 24px 24px 24px;
}
</style>
